#include <stdio.h>
#include <sys/types.h>

struct List{
	pid_t pid;
	int status;
	struct List* next;
	struct List* last;
}; typedef struct List jobs;

static jobs* job;

void addJob(pid_t pid, int status){
    jobs* new = malloc(sizeof(jobs*));
    new->pid = pid;
    new->status = status;
    if (status){
    	jobs* temp = job;
    	while (temp != NULL){
    		if (temp->status == 1) temp->status = 0; /* background */
    		temp = temp->next;
    	}
    }
    if (job == NULL){
    	job = new;
    	job->last = job;
    }
    else{
    	job->last->next = new;
    	job->last = new;
    }
    printf("%d added to the list.\n",pid);
}
void updateJob(pid_t pid, int status){
	jobs* temp = job;
	jobs* cpf = NULL;
	bool found = false;
	while(temp != NULL){
		if (temp->pid == pid){
			found = true;
			temp->status = status;
		}
		else{
			if (temp->status == 1){
				cpf = temp;
				temp->status = 0;
			}
		}
		temp = temp->next;
	}
	if (!found){
		cpf->status = 1;
		printf("Given process %d not in Jobs list.\n",pid);
	}
}
void bgJob(pid_t gpid){
	jobs* temp = job;
	while (temp != NULL){
		if (temp->pid == gpid){
			 temp->status = 1;
			 printf("%d has been moved to the background.\n",gpid);
			 fflush(stdout);
		}
		else temp->status = 0;
		temp = temp->next;
	}
}

void delJob(pid_t pid){
	jobs* temp = job;
	bool found = false;
	if (temp->pid == pid){
		job = job->next;
		job->last = job;
		temp = NULL;
		found = true;
	}
	else{
		while (temp != NULL && temp->next != NULL){
			if (temp->next->pid == pid){
				jobs* toDel = temp->next;
				temp->next = temp->next->next;
				toDel = NULL;
				if (job->last == NULL){
					job->last = temp->next;
				}
				found = true;
				printf("%d deleted from list.\n",pid);
				return;
			}
			temp = temp->next;
		}
		if(!found) printf("%d has not been found in the job list.\n",pid);
	}
}
